package vn.lumi.smarthome.ui.login;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Floor;
import vn.lumi.smarthome.network.AllStatus;
import vn.lumi.smarthome.network.Config;
import vn.lumi.smarthome.network.HC_ACK;
import vn.lumi.smarthome.network.Login;
import vn.lumi.smarthome.network.LoginFeedback;
import vn.lumi.smarthome.network.NetMessage;
import vn.lumi.smarthome.provider.SmartHomeProvider;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.MainActivity;
import vn.lumi.smarthome.ulti.ChangeFont;
import vn.lumi.smarthome.ulti.Preference;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.DetailedState;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;

public class LoginActivity extends SherlockFragmentActivity implements
		OnClickListener {

	static LumiHome myApp;

	// constants for commands to AsyncTask
	private final static int DO_NOTHING = 0;
	private final static int LOGIN = 2;

	private EditText edtUid;
	private EditText edtPwd;

	private Button btnLogin;
	private Button btnSetting;
	private int Config_ver = 0;
	private static int LastSessionID = 0;
	String userName;
	String password;

	private static boolean haveLAN = false;

	static boolean socket_working = false;

	private static boolean haveWifi = false;
	private static boolean have3G = false;
	private static boolean haveWAN = false;
	private static boolean isVersionCorrect = true;

	// Cau hinh App xem co version hay khong
	public final static boolean isConfigVersion = true; // Co version
	// ---------------------------------------------

	int versionOfHc;

	byte isUserValid;
	static boolean LoginState = false;
	GetDataSocket LoginAsyncTask;

	byte[] concat(byte[]... arrays) {
		// Determine the length of the result array
		int totalLength = 0;
		for (int i = 0; i < arrays.length; i++) {
			totalLength += arrays[i].length;
		}

		// create the result array
		byte[] result = new byte[totalLength];

		// copy the source arrays into the result array
		int currentIndex = 0;
		for (int i = 0; i < arrays.length; i++) {
			System.arraycopy(arrays[i], 0, result, currentIndex,
					arrays[i].length);
			currentIndex += arrays[i].length;
		}

		return result;
	}

	byte[] StringToByte(String str) {
		byte[] result = new byte[20];
		byte[] temp = null;
		try {
			temp = str.getBytes("UTF-16BE");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < 20; i++) {
			if (i < temp.length)
				result[i] = temp[i];
			else
				result[i] = 0;
		}
		return result;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		vn.lumi.smarthome.Config.configLanguage(getBaseContext(),
				Preference.getLanguage(getApplicationContext()));
		ActivityHelper.initialize(this);
		setContentView(R.layout.activity_login);
		myApp = (LumiHome) getApplication();

		initView();
		initData();
		Log.e("isConfigVersion", "" + isConfigVersion);
		if (!("").equals(Preference.getUID(getApplicationContext()))
				&& !("").equals(Preference.getPWD(getApplicationContext()))) {
			TryLogin();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		vn.lumi.smarthome.Config.isVibrate = Preference.getVibrate(this);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		if (vn.lumi.smarthome.Config.isVibrate)
			new VibrateThread(getApplicationContext()).start();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		 LoginAsyncTask.cancel(true);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// if(!LoginAsyncTask.isCancelled()){
		/* LoginAsyncTask.cancel(true); */
		// }
	}

	private void initView() {
		// initialize variables
		edtUid = (EditText) findViewById(R.id.activity_login_edt_username);
		edtPwd = (EditText) findViewById(R.id.activity_login_edt_pwd);
		btnLogin = (Button) findViewById(R.id.activity_login_btn_login);
		btnSetting = (Button) findViewById(R.id.activity_login_btn_Setting);

		// Check autologin --> if yes: load last time Uid and Pwd
		btnLogin.setOnClickListener(this);
		btnSetting.setOnClickListener(this);
	}

	private void initData() {
		edtPwd.setText(Preference.getPWD(getApplicationContext()));
		edtUid.setText(Preference.getUID(getApplicationContext()));

		LumiHome.LAN_ip = Preference.getLAN_IP(getApplicationContext());
		LumiHome.LAN_port = Preference.getLAN_port(getApplicationContext());
		LumiHome.DNS_address = Preference
				.getDNS_Address(getApplicationContext());
		LumiHome.WAN_port = Preference.getDNS_port(getApplicationContext());
	}

	public void TryLogin() {
		// check Uid and Pwd valid
		if (edtUid.getText().toString().length() > 10
				|| edtUid.getText().toString().length() == 0
				|| edtPwd.getText().toString().length() > 10
				|| edtPwd.getText().toString().length() == 0) {
			EraseUserInfo();

			showCustomDialog(R.string.glb_txt_error, R.string.txt_Invalid_User);
			return;
		}

		// Ask user to remove old data

		// Check Wifi, 3G
		ConnectivityManager connMgr = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final android.net.NetworkInfo wifi = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		final android.net.NetworkInfo mobile = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifi != null && wifi.isAvailable()
				&& wifi.getDetailedState() == DetailedState.CONNECTED) {
			haveWifi = true;
		} else {
			haveWifi = false;
		}

		if (mobile != null && mobile.isAvailable()
				&& mobile.getDetailedState() == DetailedState.CONNECTED) {
			have3G = true;
		} else {
			have3G = false;
		}

		if (haveWifi == false & have3G == false) {

			showCustomDialog(R.string.glb_txt_error, R.string.No_Wifi_3g);

			return;
		}

		// save user and pwd
		userName = edtUid.getText().toString();
		password = edtPwd.getText().toString();

		// Create Socket and check LAN/WAN
		socket_working = true;
		haveLAN = false;
		haveWAN = false;
		LoginAsyncTask = new GetDataSocket(this.getApplicationContext(), this,
				LOGIN);

		LoginAsyncTask.execute();

		// AsyncTask to login

	}

	public class GetDataSocket extends AsyncTask<Void, String, byte[]> {
		private LoginActivity mActivity;
		private int command = DO_NOTHING;
		LoginFeedback loginFeedback = new LoginFeedback();
		ArrayList<Device> devices = new ArrayList<Device>();
		ArrayList<Floor> floors = new ArrayList<Floor>();
		public ProgressDialog dialog;
		private Context context;

		public GetDataSocket(Context context, LoginActivity activity, int Cmd) {
			super();
			command = Cmd;
			WeakReference<LoginActivity> reference = new WeakReference<LoginActivity>(
					activity);
			mActivity = reference.get();
			this.context = context;
			this.dialog = new ProgressDialog(new ContextThemeWrapper(mActivity,
					R.style.AlertDialogCustom));

		}

		@Override
		protected void onPreExecute() {
			this.dialog.setMessage(context.getString(R.string.txt_connecting));
			this.dialog.setCancelable(false);
			this.dialog.show();
			// Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(getApplicationContext());
			TextView textView = (TextView) dialog
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					R.string.txt_connecting, LumiHome.font,
					LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
							.getColor(R.color.greenActionbar));

		}

		@Override
		protected byte[] doInBackground(Void... params) {
			if (command == LOGIN) {
				if (haveWifi == true) {
					// open socket to LAN IP
					haveLAN = mActivity.CheckHCLogin(context, dialog, "LAN",
							loginFeedback, devices, floors);
				}

				// if haveLAN = false or mobile is using 3G --> check WAN
				if (haveLAN == false) {
					haveWAN = mActivity.CheckHCLogin(context, dialog, "WAN",
							loginFeedback, devices, floors);
				}
				// So sanh version database, neu' khac' -> cap nhat config moi
				// vao db
				if ((haveLAN == true || haveWAN == true)
						&& loginFeedback.getUserValid() == LoginFeedback.LOGIN_SUCCESSFUL) {
					LumiHome.Uid = loginFeedback.getUid();
					LumiHome.Session_id = loginFeedback.getSid();
					// LumiHome.HC_Config_ver = loginFeedback.getHCConfigVer();
					LumiHome.HC_Config_ver = 0;
					SaveUserInfo();
					if (haveLAN == true)
						LumiHome.Timeout = 2000; // ms
					else if (haveWAN == true)
						LumiHome.Timeout = 3000; // ms;
					if (loginFeedback.getHCConfigVer() != LastSessionID) {
						SmartHomeProvider.insertConfigFromHCToDB(mActivity,
								floors);
						floors.clear();
					} else
						SmartHomeProvider.insertDataStateFromHCToDB(mActivity,
								devices);
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(byte[] result) {
			// test
			LoginState = true;

			super.onPostExecute(result);
			if (dialog != null && dialog.isShowing()){
				dialog.dismiss();
				dialog = null;
			}

			Log.d("onPostExecute", "run now");
			if (isVersionCorrect == false) {
				showCustomDialog(R.string.glb_txt_error,
						R.string.txt_error_version_hc_incorrect);
			}

			if (haveLAN == false && haveWAN == false
					&& isVersionCorrect == true) {
				LoginState = false;
				showCustomDialog(R.string.glb_txt_error,
						R.string.txt_error_cannot_connect_hc);
				return;
			} else {
				if (loginFeedback.getUserValid() == LoginFeedback.WRONG_USER) {
					LoginState = false;
					EraseUserInfo();
					showCustomDialog(R.string.glb_txt_error,
							R.string.txt_error_invalid_user_pwd);
					return;
				} else if (loginFeedback.getUserValid() == LoginFeedback.HC_FULL) {
					LoginState = false;
					showCustomDialog(R.string.txt_error_login_fail,
							R.string.txt_error_login_fail_in_two_device);
					return;
				} else if (loginFeedback.getUserValid() == LoginFeedback.LOGIN_SUCCESSFUL) {

					LoginState = true;
					if (LoginState == true) {
						LumiHome.SocketState = LumiHome.SOCKET_OPENED;
						startService(new Intent(LoginActivity.this,
								SmartHomeService.class));
						Intent intent = new Intent(getApplicationContext(),
								MainActivity.class);
						startActivity(intent);
						finish();
					}

				}

			}
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

	}

	public void SaveUserInfo() {
		// Lưu mật khẩu nham muc dich thay doi password
		LumiHome.password = edtPwd.getText().toString();
		Preference
				.savepwd(getApplicationContext(), edtPwd.getText().toString());
		Preference.saveRemember(getApplicationContext(), true);
		Preference
				.saveUID(getApplicationContext(), edtUid.getText().toString());

	}

	public void EraseUserInfo() {
		Preference.savepwd(getApplicationContext(), "");
		Preference.saveRemember(getApplicationContext(), false);
		Preference.saveUID(getApplicationContext(), "");
	}

	public boolean CheckHCLogin(Context context, final ProgressDialog dialog,
			String path, LoginFeedback loginFeedback,
			ArrayList<Device> devices, ArrayList<Floor> floors) {

		int openSocketRetry = 0;
		int loginRetry = 0;
		Log.d("Socket", "Openning socket to " + path + " HC");
		boolean HCConnected = false;
		while (openSocketRetry < 2) {
			try {
				LumiHome.socket = new Socket();
				LumiHome.socket.setReceiveBufferSize(10000);
				if (path == "LAN") {
					LumiHome.socket.connect(new InetSocketAddress(
							LumiHome.LAN_ip, LumiHome.LAN_port), 1000); // timeout
																		// = 3s
					LumiHome.socket.setSoTimeout(1000);

				} else if (path == "WAN") {
					LumiHome.socket.connect(new InetSocketAddress(
							LumiHome.DNS_address, LumiHome.WAN_port), 5000);
					LumiHome.socket.setSoTimeout(3000);
				}
				LumiHome.is = LumiHome.socket.getInputStream();
				LumiHome.os = LumiHome.socket.getOutputStream();
				HCConnected = true;
				break;
			} catch (IOException e) {
				e.printStackTrace();
				HCConnected = false;
				try {
					if (LumiHome.is != null)
						LumiHome.is.close();
					if (LumiHome.os != null)
						LumiHome.os.close();
					if (LumiHome.socket != null)
						LumiHome.socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				openSocketRetry++;
			}
		}

		if (HCConnected == true) {

			// send login message to HC
			Login login = new Login(LastSessionID, userName, password,
					Config_ver);
			byte[] dataout = login.generateByteArray();
			while (loginRetry < 2) {

				try {
					LumiHome.os.write(dataout);

					// String log = "";
					// for (byte b : dataout) {
					// log += " " + String.format("%x", b);
					// }

					// =========Nhan ban tin bao version
					if (isConfigVersion) {
						byte[] buffer_version = new byte[10];
						LumiHome.is.read(buffer_version, 0, 5); // 5: chieu dai
																// cua
																// ban tin bao
																// version
						if (Byte2Unsigned(buffer_version[0]) == NetMessage.CMD_APP_LOGIN) {
							if (buffer_version[4] == NetMessage.VERSION_NOT_CORRECT) {
								isVersionCorrect = false;
								versionOfHc = buffer_version[3];
								return false;
							} else if (buffer_version[4] == NetMessage.VERSION_CORRECT)
								isVersionCorrect = true;
						}
					}

					// ==========End===================

					byte[] buffer_temp = new byte[1000];
					try {
						LumiHome.is.read(buffer_temp, 0, 3);

					} catch (IOException e1) {
						// TODO Auto-generated catch block

						e1.printStackTrace();
					}
					int length = Byte2Unsigned(buffer_temp[1]) * 256
							+ Byte2Unsigned(buffer_temp[2]);
					try {
						LumiHome.is.read(buffer_temp, 1, length);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					byte[] buffer = new byte[length + 1];
					for (int i = 0; i < length + 1; i++) {
						buffer[i] = buffer_temp[i];
					}

					// log = "";
					// for (byte b : buffer) {
					// log += " " + String.format("%x", b);
					// }
					// Log.d("Socket", "Login Feedback: " + log);
					// Log.d("Socket", "login Feedback: " +
					// Arrays.toString(buffer));
					if (loginFeedback.isCorrectFormat(buffer, buffer.length) == true) {
						HCConnected = true;
						loginFeedback.parseMessage(buffer, buffer.length);
					} else
						HCConnected = false;
					break;
				} catch (IOException e) {
					Log.d("Socket", "Can not read from HC, retry="
							+ (loginRetry + 1));
					e.printStackTrace();
					HCConnected = false;
					loginRetry++;
				}
			}

			if (HCConnected == true) { // get config from HC
				// tach ban tin Login Feedback
				if (loginFeedback.getUserValid() == LoginFeedback.LOGIN_SUCCESSFUL) {
					NetMessage.numOfTMDE = 0;
					NetMessage.numOfTMSE = 0;
					try {
						LumiHome.socket.setSoTimeout(10000);
					} catch (SocketException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					if (Config_ver == loginFeedback.getHCConfigVer()) {
						// nhan ban tin device status
						floors = null;
						byte[] buffer_temp = new byte[1000];
						try {
							LumiHome.is.read(buffer_temp, 0, 3);

							int length = Byte2Unsigned(buffer_temp[1]) * 256
									+ Byte2Unsigned(buffer_temp[2]);
							LumiHome.is.read(buffer_temp, 1, length);
							byte[] buffer = new byte[length + 1];
							for (int i = 0; i < length + 1; i++) {
								buffer[i] = buffer_temp[i];
							}

							// String log = "";
							// for (byte b : buffer) {
							// log += " " + String.format("%x", b);
							// }
							// Log.d("Socket", "status: " + "length = " + length +
							// ":"
							// + log);
							// Log.d("Socket", "status: " + "length = " + length +
							// ":"
							// + Arrays.toString(buffer));
							AllStatus deviceStatus = new AllStatus(
									getApplicationContext());
							deviceStatus.parseMessage(buffer, buffer.length);
							devices = deviceStatus.getDevices();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					} else {
						// Thong bao la dang nhan ban tin cau hinh tu HC
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								dialog.setMessage(getString(R.string.txt_receiving_data_in_HC));
							}
						});
						// nhan ban tin config
						devices = null;
						byte[] buffer = new byte[10000];
						int buffer_length = 0;
						try {
							for (int i = 0;; i++) {
								byte[] buffer_temp = new byte[10000];

								LumiHome.is.read(buffer_temp, 0, 3);

								int typeMessage = 256 + (int) buffer_temp[0];
								switch (typeMessage) {
								case NetMessage.CMD_HC_CONFIG_DEVICE:
									NetMessage.numOfTMDE++;
									break;
								case NetMessage.CMD_HC_CONFIG_SCENE:
									NetMessage.numOfTMSE++;
									break;
								default:
									break;
								}

								int length = Byte2Unsigned(buffer_temp[1])
										* 256 + Byte2Unsigned(buffer_temp[2]);
								byte length1 = buffer_temp[1];
								byte length2 = buffer_temp[2];
								LumiHome.is.read(buffer_temp, 1, length);

								String len = "";
								len += "[" + String.format("%x", length1);
								len += " " + String.format("%x", length2) + "]";
								if (length > 0) {
									String log = "";
									for (int i1 = 0; i1 < length + 1; i1++) {
										log += " "
												+ String.format("%x",
														buffer_temp[i1]);
										if (i1 == 0)
											log += len;
									}
									Log.e("ban tin", "config: " + "length = "
											+ length + ":" + log);
								}

								HC_ACK ack = new HC_ACK();
								if (ack.isCorrectFormat(buffer_temp, length + 1) == true) { // Neu
																							// dung
																							// la
																							// ban
																							// tin
																							// Ack

									break;
								}
								if (i == 0) { // Neu nhan ban tin dau tien
									for (int j = 0; j < length + 1; j++) {
										buffer[j] = buffer_temp[j];
									}
									buffer_length = length + 1;
								} else {
									for (int j = 0; j < length; j++) {
										buffer[buffer_length + j] = buffer_temp[j + 1];
									}
									buffer_length += length;
								}
							}
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									dialog.setMessage(getString(R.string.txt_cotroling_data_from_HC));
								}
							});
							Config cf = new Config();
							// Log.e("size", "buffer"+ buffer.length);
							cf.parseMessage(buffer, buffer_length);

							floors.addAll(cf.getFloors());
							// floors = cf.getFloors();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									dialog.setMessage(getString(R.string.txt_can_not_receive_data_in_HC));
								}
							});
						}
					}
				}
				try {
					LumiHome.socket.setSoTimeout(3000);

					// Hieu them vao
					LumiHome.socket.setKeepAlive(true);
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return HCConnected;
	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvTitle = new TextView(getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

	public int Byte2Unsigned(byte a) {
		return a & 0xFF;
	}

	@Override
	public void onClick(View v) {
		if (vn.lumi.smarthome.Config.isVibrate)
			new VibrateThread(getApplicationContext()).start();
		switch (v.getId()) {
		case R.id.activity_login_btn_login:
			TryLogin();
			break;
		case R.id.activity_login_btn_Setting:

			View settingLayout = getLayoutInflater().inflate(
					R.layout.dialog_login_setting, null);

			final EditText edtLAN_IP = (EditText) settingLayout
					.findViewById(R.id.dialog_login_setting_edt_LAN_IP);
			final EditText edtLAN_port = (EditText) settingLayout
					.findViewById(R.id.dialog_login_setting_edt_LAN_port);
			final EditText edtDNS_Address = (EditText) settingLayout
					.findViewById(R.id.dialog_login_setting_edt_DNS);
			final EditText edtDNS_port = (EditText) settingLayout
					.findViewById(R.id.dialog_login_setting_edt_DNS_port);
			final Button btnSave = (Button) settingLayout
					.findViewById(R.id.dialog_login_setting_btn_save);
			final Button btnExit = (Button) settingLayout
					.findViewById(R.id.dialog_login_setting_btn_exit);

			edtLAN_IP.setText(LumiHome.LAN_ip);
			edtLAN_port.setText(String.valueOf(LumiHome.LAN_port));
			edtDNS_Address.setText(LumiHome.DNS_address);
			edtDNS_port.setText(String.valueOf(LumiHome.WAN_port));

			AlertDialog.Builder alert = new AlertDialog.Builder(
					new ContextThemeWrapper(this, R.style.AlertDialogCustom));
			// Thay doi font chu cua Dialog
			TextView title = new TextView(this);
			ChangeFont fontTitle = new ChangeFont(getApplicationContext());
			title = fontTitle.changeFontTextView(title, R.string.txt_setting,
					LumiHome.font, LumiHome.sizeTittle, Gravity.CENTER,
					getResources().getColor(R.color.green));
			alert.setCustomTitle(title);

			alert.setView(settingLayout);
			alert.setCancelable(false);

			final AlertDialog dialog = alert.create();
			dialog.show();

			btnSave.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// check if ports are in range 0-65535
					if (vn.lumi.smarthome.Config.isVibrate)
						new VibrateThread(getApplicationContext()).start();
					int LAN_port = 0;
					if (edtLAN_port.getText().toString().equals(""))
						LAN_port = 0;
					else
						LAN_port = Integer.parseInt(edtLAN_port.getText()
								.toString());

					int WAN_port = 0;
					if (edtDNS_port.getText().toString().equals(""))
						WAN_port = 0;
					else
						WAN_port = Integer.parseInt(edtDNS_port.getText()
								.toString());

					if (LAN_port > 65535 || WAN_port > 65535) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								LoginActivity.this);
						ChangeFont changeFont = new ChangeFont(
								getApplicationContext());
						TextView tv = new TextView(getApplicationContext());
						tv = changeFont.changeFontTextView(tv,
								getString(R.string.txt_error), LumiHome.font,
								LumiHome.sizeTittle, Gravity.CENTER,
								getResources().getColor(R.color.green));

						builder.setCustomTitle(tv);

						builder.setMessage(R.string.txt_error_port);

						builder.setNegativeButton(
								getString(R.string.glb_txt_return),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										dialog.cancel();
										if (vn.lumi.smarthome.Config.isVibrate)
											new VibrateThread(
													getApplicationContext())
													.start();
									}
								});

						showCustomDialog(R.string.glb_txt_error,
								R.string.txt_error_port);

						return;
					}

					LumiHome.LAN_ip = edtLAN_IP.getText().toString();
					Preference.saveLAN_IP(getApplicationContext(),
							LumiHome.LAN_ip);

					if (edtLAN_port.getText().toString().equals(""))
						LumiHome.LAN_port = 0;
					else
						LumiHome.LAN_port = Integer.parseInt(edtLAN_port
								.getText().toString());
					Preference.saveLAN_port(getApplicationContext(),
							LumiHome.LAN_port);

					LumiHome.DNS_address = edtDNS_Address.getText().toString();
					Preference.saveDNS_Address(getApplicationContext(),
							LumiHome.DNS_address);

					if (edtDNS_port.getText().toString().equals(""))
						LumiHome.WAN_port = 0;
					else
						LumiHome.WAN_port = Integer.parseInt(edtDNS_port
								.getText().toString());
					Preference.saveDNS_port(getApplicationContext(),
							LumiHome.WAN_port);
					dialog.cancel();
				}
			});

			btnExit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (vn.lumi.smarthome.Config.isVibrate)
						new VibrateThread(getApplicationContext()).start();
					dialog.cancel();
				}
			});
			break;
		default:
			break;
		}
	}

}
